<script setup>
import { ref, onMounted, watch } from "vue";
import { pageQueryEmp ,addEmp,getEmpById,deleteEmpById} from "@/api/emp";
import { ElMessage ,ElMessageBox} from "element-plus";
import { queryAllDepts } from "../../api/dept";
import { updateEmpById } from "../../api/emp";



const searchForm = ref({
  name: '',
  gender: '',
  begin: '',
  end: '',
  daterange: []
});
const handleSelectionChange = (val) => {
  //val是所有被选中的行数据
  multipleSelection.value = val
}

const page = ref(1);
const pageSize = ref(5);
const total = ref(0);
const tableData = ref([])
watch(() => searchForm.value.daterange, (newValue, oldValue) => {
  if (newValue && newValue.length == 2) {
    searchForm.value.begin = newValue[0];
    searchForm.value.end = newValue[1];
  }

}
)
async function search() {
  const result = await pageQueryEmp(searchForm.value, page.value, pageSize.value);
  if (result.code == 1) {
    tableData.value = result.data.rows;


    total.value = result.data.total;
  } else {
    ElMessage.error("查询员工失败")
  }



}
function research() {
  searchForm.value = {
    name: '',
    gender: '',
    begin: '',
    end: '',
    daterange: []
  };
  search();
}
const handleEdit = async (index, row) => {
  //先将后端发请求查询员工
  const result = await getEmpById(row.id);
  if(result.code==1){
    empForm.value=result.data;
  const exprlist=empForm.value.exprList;
  exprlist.forEach(expr=>
    expr.exprrange=[expr.begin,expr.end]
);

  dialogTitle.value = "修改员工"
  dialogFormVisible.value = 'true';

  }

}
const handleDelete = (index, row) => {
//先确认

  ElMessageBox.confirm(
    '此操作将永久删除该员工, 是否继续?', '提示'
    ,{
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const result = await deleteEmpById(row.id);
      if (result.code == 1) {
        ElMessage.success("删除成功");
        search();
      } else {
        ElMessage.error("删除失败")
      }
    })
    
}


onMounted(async () => {
  search();

  const result = await queryAllDepts();
  if (result.code == 1) {
    depts.value = result.data;
  }

  const loginInfoStr =localStorage.getItem("loginInfo");
  if(loginInfoStr){
    const loginInfo = JSON.parse(loginInfoStr);
    userToken.value = loginInfo.token;
  }


}
)

const handleSizeChange = (val) => {
  search();
}
const handleCurrentChange = (val) => {

  console.log(`current page: ${val}`)
  search();
}
 async function save() {
let result;
if(empForm.value.id){
  result =await updateEmpById(empForm.value);
}else{
   result =await addEmp(empForm.value);
}
 
 if(result.code==1){
  ElMessage.success("保存成功");
  dialogFormVisible.value =false;
  search();
 }else{
  ElMessage.error("保存失败")
 }
}
function showAddWin() {
  empForm.value = {
    "image": "",
    "username": "",
    "name": "",
    "gender": "",
    "job": "",
    "entryDate": "",
    "deptId": "",
    "phone": "",
    "salary": "",
    "exprList": []
  };
  dialogTitle.value = '新增员工';
  dialogFormVisible.value = true;
}


const dialogFormVisible = ref(false)
const dialogTitle = ref("新增员工")
const genders = ref([
  { value: 1, name: '男' },
  { value: 2, name: '女' }
])
const jobs = ref([
  { value: 1, name: '班主任' },
  { value: 2, name: '讲师' },
  { value: 3, name: '学工主管' },
  { value: 4, name: '教研主管' },
  { value: 5, name: '咨询师' },
]);
const depts = ref([]);
const empForm = ref({ //dialog里表单所绑定的数据对象。后期要提交到后端，所以必须与API接口文档里的参数一致
  "image": "",
  "username": "",
  "name": "",
  "gender": "",
  "job": "",
  "entryDate": "",
  "deptId": "",
  "phone": "",
  "salary": "",
  "exprList": []
});

const userToken=ref("");
const handleAvatarSuccess = (response, uploadFile) => {
  empForm.value.image=response.data;
}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/jpg'&&rawFile.type !== 'image/png') {
    ElMessage.error('不支持该图片格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('图片不能超过5MB!')
    return false
  }
  return true
}
watch(()=>empForm.value.exprList,(newValue,oldValue)=>{
  newValue.forEach(expr => {
    const range  =expr.exprrange;
    if(range && range.length==2){
      expr.begin =range[0];
      expr.end =range[1];
    }
    
  });
},{deep:true})
function addExpr(){
  empForm.value.exprList.push({ company:"", job:"", begin:"", end:""})
}
function removeExpr(index){
  empForm.value.exprList.splice(index,1);
}
</script>

<template>



  <br></br>
  <el-button type="primary" @click="showAddWin" style="margin-bottom: 20px;">
    新增员工
  </el-button>
  <el-button type="danger" @click="showAddWin" style="margin-bottom: 20px;" >
    批量删除
  </el-button>




    <!-- 新增/修改dialog -->
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle">
      <!-- 员工表单 -->
      <el-form label-width="80px" :model="empForm">
        <!-- 第1行：用户名和姓名 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名">
              <el-input v-model="empForm.username" placeholder="请输入员工用户名，2-20个字" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名">
              <el-input v-model="empForm.name" placeholder="请输入员工姓名，2-10个字" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第2行：性别和手机号 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别">
              <el-select v-model="empForm.gender" placeholder="请选择性别" style="width:100%">
                <el-option v-for="g in genders" :label="g.name" :value="g.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号">
              <el-input v-model="empForm.phone" placeholder="请输入员工手机号" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第3行：职位与薪资 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职位">
              <el-select v-model="empForm.job" placeholder="请选择职位" style="width:100%">
                <el-option v-for="j in jobs" :label="j.name" :value="j.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="薪资">
              <el-input v-model="empForm.salary" placeholder="请输入员工薪资" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第4行：所属部门与入职日期 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属部门">
              <el-select v-model="empForm.deptId" placeholder="请选择部门" style="width:100%">
                <el-option v-for="d in depts" :label="d.name" :value="d.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入职日期">
              <el-date-picker v-model="empForm.entryDate" type="date" value-format="YYYY-MM-DD" placeholder="选择入职日期"
                style="width:100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第5行：头像 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="头像">
              <el-upload class="avatar-uploader" action="/api/upload" :show-file-list="false" :headers="{'token':userToken}"
                :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <img v-if="empForm.image" :src="empForm.image" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第6行：添加工作经历按钮 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工作经历">
              <el-button type="success" @click="addExpr">添加工作经历</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第7行：工作经历 -->
        <el-row :gutter="20" v-for="(expr,index) in empForm.exprList">
          <el-col :span="9">
            <el-form-item label="时间" label-width="70px">
              <el-date-picker v-model="expr.exprrange" value-format="YYYY-MM-DD" type="daterange" range-separator="到" start-placeholder="开始日期"
                end-placeholder="结束日期" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="公司" label-width="50px">
              <el-input v-model="expr.company" placeholder="请输入公司名称" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="职位" label-width="50px">
              <el-input v-model="expr.job" placeholder="请输入职位" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-button type="danger" @click="removeExpr(index)">删除</el-button>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </template>
    </el-dialog>

  <el-form :inline="true" :model="searchForm" class="demo-form-inline">
    <el-form-item label="姓名">
      <el-input v-model="searchForm.name" placeholder="请输入员工姓名" clearable />
    </el-form-item>
    <el-form-item label="性别">
      <el-select v-model="searchForm.gender" placeholder="请选择" clearable>
        <el-option v-for="g in genders" :label="g.name" :value="g.value" />
      </el-select>
    </el-form-item>
    <el-form-item label="入职时间">
      <el-date-picker v-model="searchForm.daterange" type="daterange" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
        range-separator="到" start-placeholder="开始时间" end-placeholder="结束时间" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">查询</el-button>
      <el-button type="info" @click="research">清空</el-button>
    </el-form-item>
  </el-form>

  <el-table ref="multipleTableRef" :data="tableData" row-key="id" style="width: 100%"
    @selection-change="handleSelectionChange">
    <el-table-column type="selection" :selectable="selectable" width="55" />
    <el-table-column label="姓名" prop="name" />
    <el-table-column label="性别" prop="gender">
      <template #default="scope">{{ scope.row.gender == 1 ? '男' : '女' }}</template>
    </el-table-column>
    <el-table-column label="头像" prop="image">
      <template #default="scope"> <img :src="scope.row.image" style="height: 50px;"></template>
    </el-table-column>
    <el-table-column label="所属部门" prop="deptName" />
    <el-table-column label="职位" prop="job">
      <template #default="scope">
        <span v-if="scope.row.job == 1">班主任</span>
        <span v-else-if="scope.row.job == 2">讲师</span>
        <span v-else-if="scope.row.job == 3">学工主管</span>
        <span v-else-if="scope.row.job == 4">教研主管</span>
        <span v-else="scope.row.job==5">咨询师</span>
      </template>
    </el-table-column>
    <el-table-column label="入职日期" prop="entryDate" />
    <el-table-column label="最后操作时间" prop="updateTime" />
    <el-table-column label="操作">

      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
          编辑
        </el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
          删除
        </el-button>
      </template>

    </el-table-column>


  </el-table>

  <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
    layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
    @current-change="handleCurrentChange" />




</template>

<style scoped>
.avatar {
  height: 40px;
}

.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
  /* 添加灰色的虚线边框 */
  border: 1px dashed var(--el-border-color);
}
</style>